<template>
	<view class="_abbr">
		<view class="public">
			<view class="detail">
				<view class="main_body_view main_body_view_title">
					<u-row>
						{{dataForm.workOrderId}}
					</u-row>
				</view>
				<view class="main_body_view main_body_view_view">
					客户：{{dataForm.customerCompanyName}}
				</view>
				<!-- <view class="main_body_view main_body_view_view">
					时间：{{dataForm.preArriveCustomerTime|formatDate('MM-dd HH:mm') || ''}}
				</view>
				<view class="main_body_view">
					联系：{{dataForm.customerCompanyConnUsername || ''}}/{{dataForm.customerCompanyConnUserTel || ''}}
				</view>
				<view class="main_body_view">地址：{{dataForm.province}}/{{dataForm.city}}/{{dataForm.district}}</view>
				<view class="main_body_view">{{dataForm.recycleAddress||''}}</view> -->
				<text class="main_body_view">备注：{{dataForm.dispWorkOrderRemark||"暂无其它备注"}}</text>
			</view>
		</view>
		<view class="public">
			<!-- <view>现场要求：<text :key="item" v-for="item in dataForm.recycleLiveRequest">{{item.remark}}/</text>
			</view>
			<view>其他：{{dataForm.recycleLiveRequestOther||"无"}}</view>
			<view>现场数据：<text :key="item" v-for="item in dataForm.recycleDataDestroyType">{{item.remark}}/</text>
			</view>
			<view>其他：{{dataForm.recycleDataDestroyTypeOther||"无"}}</view> -->
			<view>检测要求：<text :key="item" v-for="item in dataForm.testDeviceRequest">{{item.remark}}/</text>
			</view>
			<view>其他：{{dataForm.testDeviceRequestOther||"无"}}</view>
			<view>检测数据：<text :key="item" v-for="item in dataForm.testDataDestroyType">{{item.remark}}/</text>
			</view>
			<view>其他：{{dataForm.testDataDestroyTypeOther||"无"}} </view>
			<!-- <view>携带设备：<text :key="item" v-for="item in dataForm.recycleTakeDevice">{{item.remark}}/</text>
			</view>
			<view>其他：{{dataForm.recycleTakeDeviceOther||"无"}}</view> -->
		</view>
		<view class="public">
			<view class="device-count">
				<view v-for="(item, index) in deviceTypeList" :key="index">
					<view class="device-item">
						<span>{{item.deviceType}}</span>
						<span>{{item.countType || 0}}/{{item.sumCountType || 0}}</span>
					</view>
				</view>
			</view>
			<view>
				<view class="scan-item item1">
					<input
						:focus="isFocus" 
						placeholder="扫描或输入二维码" 
						:value="requestParams.deviceQr" 
						@blur="confirm" 
						type="text" 
						class="input">
					<view class="right-icon">
						<view class="icon" @click="doScan1">
							<u-icon size="30" name="scan"></u-icon>
						</view>
					</view>
				</view>
				<view class="scan-item item1" v-if="ifOnlyOne">
					<input
						:focus="isFocus1" 
						placeholder="扫描或输入SN" 
						:value="requestParams.deviceSn"
						@blur="confirm1" 
						type="text" 
						class="input">
					<view class="right-icon">
						<view class="icon" @click="doScan2">
							<u-icon size="30" name="scan"></u-icon>
						</view>
					</view>
				</view>
				<view class="scan-item item1" v-if="ifOnlyOne">
					<input
						:focus="isFocus2" 
						placeholder="扫描或输入An" 
						:value="requestParams.deviceAn"
						@blur="confirm2" 
						type="text" 
						class="input">
					<view class="right-icon">
						<view class="icon" @click="doScan3">
							<u-icon size="30" name="scan"></u-icon>
						</view>
					</view>
				</view>
				<view class="scan-item item1">
					<u-input 
						v-model="deviceForm.name" 
						@tap="handleSelectDevice" 
						placeholder="选择设备" 
						border="false" 
						:show-action="false"
						>
					</u-input>
				</view>
				<view v-if="!ifOnlyOne">
					<u--input 
						placeholder="输入数量" 
						height="10rpx" 
						v-model="containerParams.count"
						>
					</u--input>
				</view>
				<view v-if="ifOnlyOne">
					<view>设备照片</view>
					<view>
						<u-upload 
							:fileList="fileList1" 
							@afterRead="afterRead" 
							@delete="deletePic" 
							name="1" 
							:maxCount="1">
						</u-upload>
					</view>
				</view>
				<view class="scan-item">
					<view class="button" v-if="ifOnlyOne">
						<u-button type="primary" @click="addDevice" text="确定添加设备" :disabled="buttonDisabled"></u-button>
					</view>
					<view class="button" v-if="!ifOnlyOne">
						<u-button type="primary" @click="addContainerDevice" text="确定添加设备" :disabled="buttonDisabled"></u-button>
					</view>
				</view>
			</view>
		</view>
		<view class="public">
			<view class="button">
				<u-button type="primary" @click="sub" text="提交" :disabled="buttonDisabled"></u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import request from '@/utils/request';
	import pickerSearch from '@/compoments/pickerSearch.vue'
	export default {
		name: 'main',
		components: {pickerSearch},
		onLoad(options) {
			uni.showLoading({
				title: "正在加载中"
			})
			this.getData(options.workId);
			this.BaseUrl = getApp().globalData.baseURL;
			// 监听生成签字的图片地址
			uni.$on('q-sign', img => {
				console.log('img', img);
				//其他操作 比如上传签字图片
				uni.uploadFile({
					url: `${this.BaseUrl}system/oss/upload`, //仅为示例，非真实的接口地址
					filePath: img,
					name: 'file',
					header: {
						Authorization: uni.getStorageSync("token")
					},
					success: (oss) => {
						const data = JSON.parse(oss.data);
						this.$nextTick();
					}
				});
			})
			uni.hideLoading()
		},
		onUnload() {
			uni.$off('q-sign') //移除监听事件
		},
		data() {
			return {
				deviceTypeList: [], //设备类型列表
				ifOnlyOne: true, //是否一物一码
				totalCount: 0, //全部数量
				isFocus1: false, // sn是否聚焦
				isFocus2: false, // an是否聚焦
				isFocus: true, // 二维码是否聚焦
				deviceForm: {}, //选择设备传递的数据
				requestParams: {
					deviceQr:null, //设备二维码
					deviceSn:null, // 设备sn
					deviceAn: null, // 资产编码
					deviceModelId:null,  // 型号
					workOrderId: null,
					deviceFlowStatus: null
				},
				containerParams: {},
				buttonDisabled: false,
				proud: "",
				BaseUrl: "",
				dataForm: {}, // 数据工单
				historyList: [], //过程工单
				subForm: {
					workOrderId: null,
					method: ""
				}, //提交工单
				WorkOrderMediaBo: [], //工单文件
				writeFlag: undefined,
				fileList1: [], //设备照片
				deviceImages: {
					deviceQr: '',
					mediaType: "1",
					mediaName: '设备照片',
					fileUrls: []
				},
			}
		},
		methods: {
			// 获取选择设备返回的参数
			otherFun(item) {
				if (item) {
					this.deviceForm = item
				}
			},
			// 二维码确定
			confirm(e) {
				this.isFocus = false
				if(e.detail.value) {
					this.requestParams.deviceQr = e.detail.value
					this.isFocus1 = true
					// 判断容器码
					let deviceQr = e.detail.value.trim().toUpperCase(); // 去除空格并转换为大写
					if (deviceQr.startsWith('CINO-C')) {
						this.ifOnlyOne = false
						this.containerParams.containerQr = e.detail.value
					}
					// else {
					// 	this.getDetail()
					// }
				}
			},
			getDetail() {
				request({
					method: "GET",
					url: `system/detail/${this.requestParams.deviceQr}`,
				}).then((res) => {
					if (res.data) {
						uni.showToast({
							title:"此设备已经添加过，不允许重复添加",
							icon:'none'
						})
					}
				})
			},
			// sn
			confirm1(e) {
				this.isFocus1 = false
				this.requestParams.deviceSn = e.detail.value
			},
			// An
			confirm2(e) {
				this.isFocus2 = false
				this.requestParams.deviceAn = e.detail.value
			},
			// 跳转选取设备
			handleSelectDevice() {
				const workId = this.dataForm.workOrderId
				uni.navigateTo({
					url: 'selectdevice/selectdevice?workId=' + workId
				});
			},
			// 扫码二维码
			doScan1() {
				uni.scanCode({
					success: (res) =>{
						this.requestParams.deviceQr = res.result
						this.isFocus1 = true
						let deviceQr = res.result.trim(); // 去除空格
						if (deviceQr.startsWith('CINO-C')) {
							this.ifOnlyOne = false
							this.containerParams.containerQr = deviceQr;
						}
						// else {
						// 	this.getDetail()
						// }
					}
				})
			},
			// 扫码sn
			doScan2() {
				uni.scanCode({
					success: (res) => {
						this.requestParams.deviceSn = res.result
						this.isFocus2 = true
					}
				})
			},
			// 扫码an
			doScan3() {
				uni.scanCode({
					success: (res) => {
						this.requestParams.deviceAn = res.result
					}
				})
			},
			goSign(num) {
				this.writeFlag = num;
				uni.navigateTo({
					url: '/uni_modules/q-sign/pages/q-sign'
				})
			},
			// 新增设备
			addDevice(){
				this.requestParams.deviceModelId = this.deviceForm.deviceModelId
				if (!this.requestParams.deviceQr) {
					uni.showToast({
						title:"请填写二维码",
						icon:'none'
					})
					return
				}
				if (!this.requestParams.deviceModelId) {
				    uni.showToast({
				        title: "请选择设备类型",
				        icon: 'none'
				    });
				    return;
				}
				this.requestParams.workOrderId = this.dataForm.workOrderId,
				this.requestParams.deviceFlowStatus = "已分拣",
				// 设备照片
				this.deviceImages.deviceQr = this.requestParams.deviceQr
				request({
					method: "GET",
					url: `system/detail/${this.requestParams.deviceQr}`,
				}).then((res) => {
					if (res.data) {
						const self = this; // 保存当前对象的引用
						uni.showModal({
							title: '该设备已经存在，是否要更改',
							success: function (res) {
								if (res.confirm) {
									// 新增设备
									request({
										url: "system/detail",
										method:"POST",
										data: self.requestParams
									}).then(res => {
										if (res.code === 200) {
											uni.showToast({
												title:"新增成功",
												icon:'none'
											})
											self.getDeviceList()
											self.reset()
										} else if (res.msg.trim().toLowerCase() === "数据库中已存在该记录，请联系管理员确认") {
											uni.showToast({
												title:"此设备已经添加过，不允许重复添加",
												icon:'none'
											})
											self.reset()
										} else {
											uni.showToast({
												title:"请扫描正确的二维码",
												icon:'none'
											})
											self.reset()
										}
									})
									// 设备照片
									if (self.deviceImages.fileUrls.length > 0) {
									    request({
									        url: 'system/modelMedia',
									        method: 'POST',
									        data: self.deviceImages
									    }).then(res => {
									        self.fileList1 = []
											self.deviceImages = {
												deviceQr: '',
												mediaType: "1",
												mediaName: '设备照片',
												fileUrls: []
											}
									    });
									}
								} else if (res.cancel) {
									self.reset()
									self.fileList1 = []
									self.deviceImages = {
										deviceQr: '',
										mediaType: "1",
										mediaName: '设备照片',
										fileUrls: []
									}
								}
							}
						})
					} else {
						const self = this;
						// 新增设备
						request({
							url: "system/detail",
							method:"POST",
							data: self.requestParams
						}).then(res => {
							if (res.code === 200) {
								uni.showToast({
									title:"新增成功",
									icon:'none'
								})
								self.getDeviceList()
								self.reset()
							} else if (res.msg.trim().toLowerCase() === "数据库中已存在该记录，请联系管理员确认") {
								uni.showToast({
									title:"此设备已经添加过，不允许重复添加",
									icon:'none'
								})
								self.reset()
							} else {
								uni.showToast({
									title:"请扫描正确的二维码",
									icon:'none'
								})
								self.reset()
							}
						})
						// 设备照片
						if (self.deviceImages.fileUrls.length > 0) {
						    request({
						        url: 'system/modelMedia',
						        method: 'POST',
						        data: self.deviceImages
						    }).then(res => {
						        self.fileList1 = []
								self.deviceImages = {
									deviceQr: '',
									mediaType: "1",
									mediaName: '设备照片',
									fileUrls: []
								}
						    });
						}
					}
				})
			},
			// 新增容器码设备
			addContainerDevice() {
				this.containerParams.deviceModelId = this.deviceForm.deviceModelId
				this.containerParams.unit = this.deviceForm.unit
				this.containerParams.orderId = this.dataForm.workOrderId,
				this.containerParams.operate = "增加"
				this.containerParams.operatePhase = this.dataForm.workOrderStatus
				this.containerParams.operatePhaseId = this.dataForm.workOrderStatusId
				request({
					url: "system/containerOperate",
					method:"POST",
					data: this.containerParams
				}).then(res => {
					if (res.code === 200) {
						uni.showToast({
							title:"新增成功",
							icon:'none'
						})
						this.getDeviceList()
						this.reset()
					} else {
						uni.showToast({
							title: res.msg,
							icon:'none'
						})
					}
				})
			},
			reset() {
				this.requestParams = {
					deviceQr: '', //设备二维码
					deviceSn: '', // 设备sn
					workOrderId: null,
					deviceAn: ''
				}
				this.containerParams = {
					containerQr: null,
					orderId: null,
					deviceModelId: null
				}
				this.ifOnlyOne = true
			},
			// 提交工单
			sub() {
				this.subForm.workOrderId = this.dataForm.workOrderId
				this.subForm.method = "sort_end"
				const self = this; // 保存当前对象的引用
				uni.showModal({
					title: '确定结束分拣吗',
					success: function (res) {
						if (res.confirm) {
							// 提交
							request({
								url: 'system/order',
								method: "PUT",
								data: self.subForm
							}).then(res => {
								uni.reLaunch({
									url: '/pages/view/sorting/index'
								})
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.forEach((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url, event.name)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url, name) {
				return new Promise((resolve, reject) => {
					uni.$u.http.upload(`${this.BaseUrl}system/oss/upload`, {
						params: {},
						/* 会加在url上 */
						// #ifdef APP-PLUS || H5
						files: [], // 需要上传的文件列表。使用 files 时，filePath 和 name 不生效。App、H5（ 2.6.15+）
						// #endif
						filePath: url, // 要上传文件资源的路径。
						// 注：如果局部custom与全局custom有同名属性，则后面的属性会覆盖前面的属性，相当于Object.assign(全局，局部)
						custom: {
							auth: true
						}, // 可以加一些自定义参数，在拦截器等地方使用。比如这里我加了一个auth，可在拦截器里拿到，如果true就传token
						name: 'file', // 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
						// #ifdef H5 || APP-PLUS
						timeout: 60000, // H5(HBuilderX 2.9.9+)、APP(HBuilderX 2.9.9+)
						// #endif
						header: {
							Authorization: uni.getStorageSync("token")
						},
						/* 会与全局header合并，如有同名属性，局部覆盖全局 */
						formData: {}, // HTTP 请求中其他额外的 form data
						// 返回当前请求的task, options。请勿在此处修改options。非必填
						getTask: (task, options) => {},
					}).then((res) => {
						// console.log(res);
						if (name == 1) {
							this.deviceImages.fileUrls.push(
								res.data.data.url.replace("blob:", ""),
							)
						}
						resolve(res.data.data.url)
						// 返回的res.data 已经进行JSON.parse
					}).catch(err => {

					})
				})
			},
			// 请求数据
			getData(workId) {
				request({
					method: "GET",
					url: `system/order/${workId}`
				}).then(res => {
					this.dataForm = res.data;
					this.getDeviceList()
					this.subForm.workOrderId = res.data.workOrderId;
					this.proud = res.data.workOrderStatusId - 0;
					this.demark(res.data);
				})
			},
			getDeviceList() {
				// console.log(11)
				request({
					method: "GET",
					url: 'system/detail/statistics',
					data: {
						workOrderId: this.dataForm.workOrderId,
						deviceFlowStatus:"已分拣",
						operatePhase: "分拣中-分拣"
					}
				}).then(res => {
					this.deviceTypeList = res.rows
				})
			},
	
			// 存储图片
			checkImages(imageForms) {
				for (let dataElement of imageForms) {
					switch (dataElement.mediaType) {
						case "1": 
							if (dataElement.fileUrl !== null) {
								this.fileList1.push({
									type: "image",
									url: dataElement.fileUrl,
									status: "success",
									name: "",
									message: "",
									thumb: "",
									size: 60489
								})
							}
						default:
							continue;
					}
				}
			},
			// 流程
			demark(data) {
				this.historyList.push({
					id: 0,
					descTime: data.preArriveCustomerTime,
					title: '预计上门时间',
					istrue: !!data.preArriveCustomerTime && true
				}, {
					id: 1,
					descTime: data.pickOrderTime,
					title: '确定接单时间',
					istrue: !!data.pickOrderTime && true
				}, {
					id: 2,
					descTime: data.arriveCustomerTime,
					title: '上门时间',
					istrue: !!data.arriveCustomerTime && true
				}, {
					id: 3,
					descTime: data.startRecycleTime,
					title: '开始回收时间 ',
					istrue: !!data.startRecycleTime && true
				}, {
					id: 4,
					descTime: data.endRecycleTime,
					title: '结束回收时间',
					istrue: !!data.endRecycleTime && true
				})
			}
		},
		filters: {
			formatDate: function(value, args) {
				var dt = new Date(value);
				if (args == 'yyyy-M-d') { // yyyy-M-d
					let year = dt.getFullYear();
					let month = dt.getMonth() + 1;
					let date = dt.getDate();
					return `${year}-${month}-${date}`;
				} else if (args == 'yyyy-M-d H:m:s') { // yyyy-M-d H:m:s
					let year = dt.getFullYear();
					let month = dt.getMonth() + 1;
					let date = dt.getDate();
					let hour = dt.getHours();
					let minute = dt.getMinutes();
					let second = dt.getSeconds();
					return `${year}-${month}-${date} ${hour}:${minute}:${second}`;
				} else if (args == 'yyyy-MM-dd') { // yyyy-MM-dd
					let year = dt.getFullYear();
					let month = (dt.getMonth() + 1).toString().padStart(2, '0');
					let date = dt.getDate().toString().padStart(2, '0');
					return `${year}-${month}-${date}`;
				} else { // yyyy-MM-dd HH:mm:ss
					let year = dt.getFullYear();
					let month = (dt.getMonth() + 1).toString().padStart(2, '0');
					let date = dt.getDate().toString().padStart(2, '0');
					let hour = dt.getHours().toString().padStart(2, '0');
					let minute = dt.getMinutes().toString().padStart(2, '0');
					let second = dt.getSeconds().toString().padStart(2, '0');
					return `${month}-${date} ${hour}:${minute}`;
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	._abbr {
		width: 100%;
		height: 100%;
		// position: absolute;
		background-color: rgba(244, 249, 254, 1);

		.public {
			background-color: #ffffff;
			margin: 20upx;
			border-radius: 2%;
			padding: 20upx;
			border:1px solid;
			border-color:rgba(0, 124, 233, 0.4);
			.main_body_view {
				margin: 10upx;
			}
			.device-count {
				display: flex;
				margin: 10px 0;
				flex-flow: row wrap;
				align-content: flex-start;
				justify-content: flex-start;
				>view {
					box-sizing: border-box;
					flex: 0 0 33%;
					text-align: center;
				}
				.device-item {
					
					display: flex;
					flex-direction: column;
					padding:5px;
				}
			}
			.main_body_view_title {
				border-bottom: 1px solid black;
				margin-bottom: 10upx;
			}
			.total-count {
				display: flex;
				align-items: center;
				justify-content: center; 
				margin-top: 10px; 
				font-size: 16px;
			}
			.scan-item {
				margin: 20upx 0;
				.input {
					margin: 10px 0 10px 6px;
					width: 100%;
				}
				.right-icon {
					position: relative;
					box-sizing: border-box;
					position: sticky;
					top: 0;
					z-index: 999;
					display: flex;
					overflow: hidden;
					justify-content: space-around;
					background: rgb(255, 255, 255);
					margin: 6px;
					.scan {
						position: absolute;
						top: 10upx;
						right:14upx;
					}
				}
				.device {
					display: flex;
					margin: 10px 0;
					justify-content: space-between;
				}
				.device-item {
					display: flex;
					align-items: center;
					flex-direction: column;
				}
				.test-scan {
					border: 1px solid #eee;
					padding: 8px;
				}
				.button {
					text-align: center; 
					margin-top: 40rpx;
					display: flex;
				}
			}
			.item1 {
				display: flex; 
				border: 1px solid #eee;
			}
			.user_for {
				display: flex;
			}
			.line_for {
				width: 4rpx;
				height: 24rpx;
				margin: 0 20rpx 10rpx;
			}
			.line_radio {
				width: 20rpx;
				height: 20rpx;
				border-radius: 50%;
				position: relative;
				left: 50%;
				transform: translateX(-50%);
				top: 0;
			}
			.right_box {
				padding: 0rpx 20rpx 20rpx 20rpx;
			}
			.desc {
				font-size: 30rpx;
				display: flex;
				margin-top: 20rpx;
				align-items: center;
			}
		}
		.write {
			display: flex;
			justify-content: space-around;
			.im {
				width: 300rpx;
				image {
					width: 200rpx;
					height: 300rpx;
					position: relative;
					left: 30rpx;
				}
			}
		}
	}
</style>
